#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <mysql/mysql.h>

#include "../../comm/log.hpp"
#include "../../comm/mysql_connection_pool/ConnectionPool.hpp"

namespace ns_model
{
    using namespace ns_log;
    // 章节
    struct chapter
    {
        std::string _chapter_id;   // 章节号
        std::string _chapter_name; // 章节名
        std::string _text;         // 章节正文
    };

    // mysql登录参数
    const std::string host = "127.0.0.1";
    const std::string user = "novel_web_client";
    const std::string passwd = "yy20040706";
    const std::string db = "novel_web";
    const int port = 3306;

    class model
    {
    public:
        model()
        {
        }
        ~model()
        {
        }

    public:
        bool queryMysql(const std::string sql, chapter *chp)
        {
            // 获取mysql连接池
            connectionPool *cp = connectionPool::getConnectionPool();
            if (cp == nullptr)
            {
                LOG(FATAL) << "MySQL连接池创建失败"
                           << "\n";
                return false;
            }
            // 获取连接
            std::shared_ptr<connection> conn = cp->getConnection();
            // 执行sql语句
            MYSQL_RES *res = conn->query(sql);
            if (res == nullptr)
            {
                return false;
            }
            // 分析结果
            MYSQL_ROW row = mysql_fetch_row(res);

            chp->_chapter_id = row[0];
            chp->_chapter_name = row[1];
            chp->_text = row[2];

            mysql_free_result(res);

            return true;
        }

        // 获取章节
        bool getOneChapter(const std::string &book_id, const std::string &chapter_id, chapter *chp)
        {
            std::string sql = "select * from book_";
            sql += book_id;
            sql += " ";
            sql += "where chapter_id = ";
            sql += chapter_id;
            return queryMysql(sql, chp);
        }
    };
}